// Copyright (c) 2023 坚果派
// 公众号：nutpi
// 电话：17752170152
// 官网：https://www.nutpi.net/
// All rights reserved.

import 'package:flutter/foundation.dart';
import 'dart:convert';
import '../models/health_news.dart';
import '../models/health_tip.dart';
import '../services/cache_service.dart';

enum BookmarkType {
  news,
  tip,
  reminder,
}

class BookmarkItem {
  final String id;
  final String title;
  final String description;
  final String imageUrl;
  final String source;
  final String url;
  final BookmarkType type;
  final DateTime dateAdded;

  BookmarkItem({
    required this.id,
    required this.title,
    required this.description,
    required this.imageUrl,
    required this.source,
    required this.url,
    required this.type,
    DateTime? dateAdded,
  }) : dateAdded = dateAdded ?? DateTime.now();

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'description': description,
      'imageUrl': imageUrl,
      'source': source,
      'url': url,
      'type': type.index,
      'dateAdded': dateAdded.toIso8601String(),
    };
  }

  factory BookmarkItem.fromJson(Map<String, dynamic> json) {
    return BookmarkItem(
      id: json['id'],
      title: json['title'],
      description: json['description'],
      imageUrl: json['imageUrl'],
      source: json['source'],
      url: json['url'],
      type: BookmarkType.values[json['type']],
      dateAdded: DateTime.parse(json['dateAdded']),
    );
  }

  factory BookmarkItem.fromHealthNews(HealthNews news) {
    return BookmarkItem(
      id: news.id,
      title: news.title,
      description: news.description,
      imageUrl: news.picUrl,
      source: news.source,
      url: news.url,
      type: BookmarkType.news,
    );
  }

  factory BookmarkItem.fromHealthTip(HealthTip tip, String tipId) {
    return BookmarkItem(
      id: tipId,
      title: tip.title,
      description: tip.content,
      imageUrl: '',
      source: '健康小妙招',
      url: '',
      type: BookmarkType.tip,
    );
  }
}

class BookmarksProvider with ChangeNotifier {
  List<BookmarkItem> _bookmarks = [];
  final CacheService _cacheService = CacheService();
  static const String _bookmarksKey = 'user_bookmarks';

  List<BookmarkItem> get bookmarks => _bookmarks;

  BookmarksProvider() {
    _loadBookmarks();
  }

  Future<void> _loadBookmarks() async {
    final data = await _cacheService.getData(_bookmarksKey);
    if (data != null) {
      _bookmarks = List<BookmarkItem>.from(
        (data as List).map((item) => BookmarkItem.fromJson(item)),
      );
      notifyListeners();
    }
  }

  Future<void> _saveBookmarks() async {
    final jsonData = _bookmarks.map((bookmark) => bookmark.toJson()).toList();
    await _cacheService.saveData(_bookmarksKey, jsonData);
  }

  bool isBookmarked(String id) {
    return _bookmarks.any((bookmark) => bookmark.id == id);
  }

  Future<void> toggleBookmark(BookmarkItem item) async {
    final existingIndex =
        _bookmarks.indexWhere((bookmark) => bookmark.id == item.id);

    if (existingIndex >= 0) {
      _bookmarks.removeAt(existingIndex);
    } else {
      _bookmarks.add(item);
    }

    notifyListeners();
    await _saveBookmarks();
  }

  Future<void> removeBookmark(String id) async {
    _bookmarks.removeWhere((bookmark) => bookmark.id == id);
    notifyListeners();
    await _saveBookmarks();
  }

  List<BookmarkItem> getBookmarksByType(BookmarkType type) {
    return _bookmarks.where((bookmark) => bookmark.type == type).toList();
  }
}
